<template>
  <div class="bg-white rounded-xl shadow-sm overflow-hidden">
    <!-- 头部区域 -->
    <div class="p-6 border-b border-gray-100">
      <div class="flex justify-between items-center">
        <h3 class="text-xl font-semibold text-gray-800">{{ title }}</h3>
        <div v-if="showButtons" class="flex gap-3">
          <button 
            class="inline-flex items-center px-4 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 transition-colors duration-200"
            @click="toggleEditMode"
          >
            <i class="ri-edit-line mr-2 text-lg"></i>
            {{ editing ? '保存' : '编辑' }}
          </button>
          <button 
            class="inline-flex items-center px-4 py-2 text-sm font-medium text-red-600 bg-red-50 rounded-lg hover:bg-red-100 transition-colors duration-200"
            @click="clearData"
          >
            <i class="ri-delete-bin-line mr-2 text-lg"></i>
            清空
          </button>
          <button 
            class="inline-flex items-center px-4 py-2 text-sm font-medium text-green-600 bg-green-50 rounded-lg hover:bg-green-100 transition-colors duration-200"
            @click="exportTemplate"
          >
            <i class="ri-download-line mr-2 text-lg"></i>
            导出
          </button>
          <div class="relative">
            <input
              ref="fileInput"
              type="file"
              accept=".xlsx,.xls"
              class="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
              @change="handleFileChange"
            />
            <button 
              type="button"
              class="inline-flex items-center px-4 py-2 text-sm font-medium text-purple-600 bg-purple-50 rounded-lg hover:bg-purple-100 transition-colors duration-200"
            >
              <i class="ri-upload-line mr-2 text-lg"></i>
              导入
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="overflow-x-auto">
      <table class="min-w-full divide-y divide-gray-200">
        <thead class="bg-gray-50">
          <tr>
            <th v-for="column in columnsRef" 
                :key="column.prop"
                class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider"
                :style="{ width: column.width, minWidth: column.minWidth }"
            >
              {{ column.label }}
            </th>
          </tr>
        </thead>
        <tbody class="bg-white divide-y divide-gray-200">
          <tr v-for="(row, index) in localData" :key="index">
            <td v-for="column in columnsRef" 
                :key="column.prop"
                class="px-6 py-4 text-sm text-gray-900"
                :class="{'whitespace-normal break-words': column.wrap}"
            >
              <el-input 
                v-if="editing" 
                v-model="row[column.prop]" 
                class="w-full"
                size="small"
              />
              <span v-else>{{ row[column.prop] }}</span>
            </td>
          </tr>
        </tbody>
      </table>

      <!-- 空状态展示 -->
      <div v-if="localData.length === 0" 
           class="flex flex-col items-center justify-center py-12 bg-gray-50">
        <i class="ri-file-list-3-line text-4xl text-gray-400 mb-3"></i>
        <p class="text-gray-500">暂无数据</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, toRef, computed } from 'vue';
import * as XLSX from 'xlsx';
import { ElMessage, ElInput } from 'element-plus';
import 'element-plus/dist/index.css';

const props = defineProps({
  title: {
    type: String,
    default: '表格明细'
  },
  data: {
    type: Array,
    default: () => []
  },
  columns: {
    type: Array,
    required: true
  },
  showButtons: {
    type: Boolean,
    default: true
  }
});

const emit = defineEmits(['update:data']);

const editing = ref(false);
const localData = ref([...props.data]);
const columnsRef = toRef(props, 'columns');
const fileInput = ref(null);

watch(() => props.data, (newValue) => {
  localData.value = [...newValue];
}, { deep: true });

const toggleEditMode = () => {
  editing.value = !editing.value;
  if (!editing.value) {
    emit('update:data', localData.value);
    ElMessage.success('保存成功');
  }
};

const clearData = () => {
  localData.value = [];
  emit('update:data', []);
  ElMessage.info('表格已清空');
};

const exportTemplate = () => {
  const headers = columnsRef.value.map(col => col.label);
  const rows = localData.value.map(row => 
    columnsRef.value.map(col => row[col.prop] || '')
  );
  const excelData = [headers, ...rows];

  const ws = XLSX.utils.aoa_to_sheet(excelData);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, "数据导出");
  XLSX.writeFile(wb, `${props.title}_${new Date().toLocaleDateString()}.xlsx`);
};

const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (!file) return;

  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                 file.type === 'application/vnd.ms-excel';
  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件！');
    return;
  }

  const reader = new FileReader();
  reader.onload = (e) => {
    try {
      const data = new Uint8Array(e.target.result);
      const workbook = XLSX.read(data, { type: 'array' });
      
      const sheet = workbook.Sheets[workbook.SheetNames[0]];
      const importedData = XLSX.utils.sheet_to_json(sheet, { header: 1 });
      
      // 移除表头
      importedData.shift();

      // 将导入的数据映射到正确的字段结构
      const newData = importedData.map(row => {
        const newRow = {};
        props.columns.forEach((col, index) => {
          newRow[col.prop] = row[index] || '';
        });
        return newRow;
      });

      // 更新数据
      localData.value = newData;
      emit('update:data', newData);
      
      // 修改成功提示的显示方式
      ElMessage({
        message: '数据导入成功',
        type: 'success',
        duration: 2000,
        showClose: true,
        offset: 80
      });
      
    } catch (error) {
      console.error('导入错误:', error);
      ElMessage.error('导入失败，请检查文件格式');
    }
  };

  reader.readAsArrayBuffer(file);
  // 清除文件输入值，允许重复选择相同文件
  event.target.value = '';
};
</script>

<style scoped>
.el-input {
  @apply transition-all duration-200;
}

.el-input:hover {
  @apply shadow-sm;
}

/* 自定义滚动条样式 */
.overflow-x-auto {
  scrollbar-width: thin;
  scrollbar-color: #E5E7EB transparent;
}

.overflow-x-auto::-webkit-scrollbar {
  height: 6px;
}

.overflow-x-auto::-webkit-scrollbar-track {
  @apply bg-transparent;
}

.overflow-x-auto::-webkit-scrollbar-thumb {
  @apply bg-gray-200 rounded-full;
}

.overflow-x-auto::-webkit-scrollbar-thumb:hover {
  @apply bg-gray-300;
}
</style>